﻿// 内容脚本 - 在网页中运行，与后台脚本通信
import type { PlasmoCSConfig } from "plasmo"

export const config: PlasmoCSConfig = {
  matches: ["<all_urls>"],
  all_frames: false
}

// 全局状态
let isRegistered = false
let lastHeartbeat = Date.now()
let heartbeatInterval: NodeJS.Timeout | null = null
let reconnectInterval: NodeJS.Timeout | null = null
let currentSessionId = ""

// 向后台脚本发送消息
async function sendToBackground(message: any) {
  try {
    return await chrome.runtime.sendMessage(message)
  } catch (error) {
    console.log("发送消息到后台脚本失败:", error)
    return null
  }
}

// 注册当前标签页
async function registerTab() {
  if (isRegistered) return
  
  const response = await sendToBackground({
    type: "REGISTER_TAB"
  })
  
  if (response?.success) {
    isRegistered = true
    console.log(" 标签页已注册到插件生命周期")
  }
}

// 注销当前标签页
async function unregisterTab() {
  if (!isRegistered) return
  
  const response = await sendToBackground({
    type: "UNREGISTER_TAB"
  })
  
  if (response?.success) {
    isRegistered = false
    console.log(" 标签页已从插件生命周期注销")
  }
}

// 更新活动状态
async function updateActivity() {
  await sendToBackground({
    type: "UPDATE_ACTIVITY"
  })
}

// 获取插件状态
async function getPluginState() {
  return await sendToBackground({
    type: "GET_PLUGIN_STATE"
  })
}

// 启动心跳监听
function startHeartbeatListener() {
  if (heartbeatInterval) {
    clearInterval(heartbeatInterval)
  }
  
  heartbeatInterval = setInterval(async () => {
    const now = Date.now()
    if (now - lastHeartbeat > 60000) { // 超过1分钟没有心跳
      console.log(" 心跳超时，尝试重新连接")
      await attemptReconnection()
    }
  }, 30000) // 每30秒检查一次
}

// 尝试重新连接
async function attemptReconnection() {
  console.log(" 尝试重新连接到后台脚本")
  
  const state = await getPluginState()
  if (state) {
    console.log(" 重新连接成功")
    lastHeartbeat = Date.now()
    updatePluginIndicator({
      sessionTime: Date.now() - state.startTime,
      activeTabsCount: state.activeTabs.length,
      sessionId: state.sessionId
    })
  } else {
    console.log(" 重新连接失败")
    showConnectionError()
  }
}

// 启动重连机制
function startReconnectionMechanism() {
  if (reconnectInterval) {
    clearInterval(reconnectInterval)
  }
  
  reconnectInterval = setInterval(async () => {
    if (!isRegistered) {
      console.log(" 检测到未注册，尝试重新注册")
      await registerTab()
    }
    
    // 检查连接状态
    const state = await getPluginState()
    if (!state) {
      console.log(" 检测到连接断开，尝试重连")
      await attemptReconnection()
    }
  }, 15000) // 每15秒检查一次
}

// 显示连接错误
function showConnectionError() {
  const indicator = document.getElementById("plugin-lifecycle-indicator")
  if (indicator) {
    indicator.style.backgroundColor = "rgba(220, 53, 69, 0.9)"
    indicator.innerHTML = `
      <div style="display: flex; align-items: center; gap: 8px;">
        <div style="width: 8px; height: 8px; background: #dc3545; border-radius: 50%;"></div>
        <span>连接断开</span>
        <span style="opacity: 0.8;">重连中...</span>
      </div>
    `
  }
}

// 监听来自后台脚本的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log(" 内容脚本收到消息:", message)
  
  switch (message.type) {
    case "HEARTBEAT":
      lastHeartbeat = Date.now()
      currentSessionId = message.data.sessionId
      console.log(" 收到心跳:", message.data)
      
      // 更新页面上的插件状态指示器
      updatePluginIndicator(message.data)
      break
      
    case "PLUGIN_COMMAND":
      handlePluginCommand(message.command, message.data)
      break
      
    case "BROADCAST_MESSAGE":
      handleBroadcastMessage(message.data)
      break
  }
  
  sendResponse({ received: true })
})

// 更新插件状态指示器
function updatePluginIndicator(data: any) {
  // 创建或更新状态指示器
  let indicator = document.getElementById("plugin-lifecycle-indicator")
  
  if (!indicator) {
    indicator = document.createElement("div")
    indicator.id = "plugin-lifecycle-indicator"
    indicator.style.cssText = `
      position: fixed;
      top: 10px;
      right: 10px;
      background: rgba(0, 123, 255, 0.9);
      color: white;
      padding: 8px 12px;
      border-radius: 6px;
      font-size: 12px;
      font-family: Arial, sans-serif;
      z-index: 10000;
      box-shadow: 0 2px 8px rgba(0,0,0,0.2);
      transition: all 0.3s ease;
      cursor: pointer;
    `
    
    // 添加点击事件，显示详细信息
    indicator.addEventListener("click", () => {
      showPluginDetails(data)
    })
    
    document.body.appendChild(indicator)
  }
  
  const sessionTime = Math.floor(data.sessionTime / 1000)
  const minutes = Math.floor(sessionTime / 60)
  const seconds = sessionTime % 60
  
  indicator.style.backgroundColor = "rgba(0, 123, 255, 0.9)"
  indicator.innerHTML = `
    <div style="display: flex; align-items: center; gap: 8px;">
      <div style="width: 8px; height: 8px; background: #28a745; border-radius: 50%; animation: pulse 2s infinite;"></div>
      <span>插件活跃</span>
      <span style="opacity: 0.8;">${minutes}:${seconds.toString().padStart(2, '0')}</span>
    </div>
  `
  
  // 添加脉冲动画
  if (!document.getElementById("plugin-pulse-style")) {
    const style = document.createElement("style")
    style.id = "plugin-pulse-style"
    style.textContent = `
      @keyframes pulse {
        0% { opacity: 1; }
        50% { opacity: 0.5; }
        100% { opacity: 1; }
      }
    `
    document.head.appendChild(style)
  }
}

// 显示插件详细信息
function showPluginDetails(data: any) {
  const modal = document.createElement("div")
  modal.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    z-index: 10002;
    display: flex;
    align-items: center;
    justify-content: center;
  `
  
  const content = document.createElement("div")
  content.style.cssText = `
    background: white;
    padding: 20px;
    border-radius: 8px;
    max-width: 400px;
    width: 90%;
    font-family: Arial, sans-serif;
  `
  
  const sessionTime = Math.floor(data.sessionTime / 1000)
  const minutes = Math.floor(sessionTime / 60)
  const seconds = sessionTime % 60
  
  content.innerHTML = `
    <h3 style="margin-top: 0;">插件状态详情</h3>
    <p><strong>状态:</strong> ${data.isActive ? '活跃' : '非活跃'}</p>
    <p><strong>会话时间:</strong> ${minutes}分${seconds}秒</p>
    <p><strong>活跃标签页:</strong> ${data.activeTabsCount} 个</p>
    <p><strong>会话ID:</strong> ${data.sessionId || '未知'}</p>
    <button onclick="this.parentElement.parentElement.remove()" style="
      background: #007bff;
      color: white;
      border: none;
      padding: 8px 16px;
      border-radius: 4px;
      cursor: pointer;
      margin-top: 10px;
    ">关闭</button>
  `
  
  modal.appendChild(content)
  document.body.appendChild(modal)
  
  // 点击背景关闭
  modal.addEventListener("click", (e) => {
    if (e.target === modal) {
      modal.remove()
    }
  })
}

// 处理插件命令
function handlePluginCommand(command: string, data: any) {
  console.log(" 执行插件命令:", command, data)
  
  switch (command) {
    case "SHOW_NOTIFICATION":
      showPageNotification(data.message, data.type || "info")
      break
      
    case "HIGHLIGHT_ELEMENT":
      highlightElement(data.selector)
      break
      
    case "SCROLL_TO_ELEMENT":
      scrollToElement(data.selector)
      break
      
    case "EXTRACT_DATA":
      extractPageData(data.selectors)
      break
  }
}

// 处理广播消息
function handleBroadcastMessage(data: any) {
  console.log(" 收到广播消息:", data)
  
  // 在页面上显示广播消息
  showPageNotification(data.message || "收到广播消息", "broadcast")
}

// 显示页面通知
function showPageNotification(message: string, type: string = "info") {
  const notification = document.createElement("div")
  notification.style.cssText = `
    position: fixed;
    top: 50px;
    right: 10px;
    background: ${type === "error" ? "#dc3545" : type === "success" ? "#28a745" : type === "broadcast" ? "#6f42c1" : "#007bff"};
    color: white;
    padding: 12px 16px;
    border-radius: 6px;
    font-size: 14px;
    font-family: Arial, sans-serif;
    z-index: 10001;
    box-shadow: 0 4px 12px rgba(0,0,0,0.3);
    max-width: 300px;
    word-wrap: break-word;
    animation: slideIn 0.3s ease;
  `
  
  notification.textContent = message
  
  // 添加滑入动画
  if (!document.getElementById("plugin-notification-style")) {
    const style = document.createElement("style")
    style.id = "plugin-notification-style"
    style.textContent = `
      @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
      }
    `
    document.head.appendChild(style)
  }
  
  document.body.appendChild(notification)
  
  // 3秒后自动移除
  setTimeout(() => {
    if (notification.parentNode) {
      notification.style.animation = "slideIn 0.3s ease reverse"
      setTimeout(() => {
        notification.remove()
      }, 300)
    }
  }, 3000)
}

// 高亮元素
function highlightElement(selector: string) {
  const element = document.querySelector(selector)
  if (element) {
    element.style.outline = "3px solid #ffc107"
    element.style.outlineOffset = "2px"
    
    setTimeout(() => {
      element.style.outline = ""
      element.style.outlineOffset = ""
    }, 3000)
  }
}

// 滚动到元素
function scrollToElement(selector: string) {
  const element = document.querySelector(selector)
  if (element) {
    element.scrollIntoView({ behavior: "smooth", block: "center" })
  }
}

// 提取页面数据
function extractPageData(selectors: Record<string, string>) {
  const data: Record<string, any> = {}
  
  for (const [key, selector] of Object.entries(selectors)) {
    const element = document.querySelector(selector)
    if (element) {
      data[key] = element.textContent?.trim() || element.getAttribute("value") || ""
    }
  }
  
  console.log(" 提取的页面数据:", data)
  return data
}

// 监听页面活动
function trackPageActivity() {
  let lastActivity = Date.now()
  
  const activityEvents = ["mousedown", "mousemove", "keypress", "scroll", "touchstart", "click"]
  
  activityEvents.forEach(event => {
    document.addEventListener(event, () => {
      const now = Date.now()
      if (now - lastActivity > 5000) { // 5秒内有活动
        updateActivity()
        lastActivity = now
      }
    }, { passive: true })
  })
}

// 页面加载完成时初始化
if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", initialize)
} else {
  initialize()
}

async function initialize() {
  console.log(" 内容脚本初始化")
  
  // 注册当前标签页
  await registerTab()
  
  // 启动心跳监听
  startHeartbeatListener()
  
  // 启动重连机制
  startReconnectionMechanism()
  
  // 开始跟踪页面活动
  trackPageActivity()
  
  // 获取插件状态
  const state = await getPluginState()
  if (state) {
    currentSessionId = state.sessionId
    updatePluginIndicator({
      sessionTime: Date.now() - state.startTime,
      activeTabsCount: state.activeTabs.length,
      sessionId: state.sessionId
    })
  }
  
  console.log(" 内容脚本初始化完成")
}

// 页面卸载时清理
window.addEventListener("beforeunload", () => {
  unregisterTab()
})

// 页面隐藏时暂停活动
document.addEventListener("visibilitychange", () => {
  if (document.hidden) {
    console.log(" 页面隐藏")
  } else {
    console.log(" 页面显示")
    updateActivity()
  }
})

export {}